﻿import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_scaffold/common/utils/toast_util.dart';
import 'package:image_picker/image_picker.dart';
import 'package:dio/dio.dart' as dio;
import 'package:azring/core/repository/default_api.dart';
import '../routes.dart';

class FeedbackLogic extends GetxController {
  final descriptionController = TextEditingController();
  final contactController = TextEditingController();
  final imageList = <File>[].obs;
  final ImagePicker _picker = ImagePicker();
  final isSubmitting = false.obs;

  @override
  void onClose() {
    descriptionController.dispose();
    contactController.dispose();
    super.onClose();
  }

  /// 选择图片
  Future<void> pickImage() async {
    if (imageList.length >= 3) {
      Toast.show('最多上传3张图片');
      return;
    }

    try {
      final XFile? image = await _picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1920,
        maxHeight: 1920,
        imageQuality: 85,
      );

      if (image != null) {
        imageList.add(File(image.path));
      }
    } catch (e) {
      Toast.show('选择图片失败');
    }
  }

  /// 删除图片
  void removeImage(int index) {
    if (index >= 0 && index < imageList.length) {
      imageList.removeAt(index);
    }
  }

  /// 提交反馈
  Future<void> submitFeedback() async {
    if (descriptionController.text.trim().isEmpty) {
      Toast.show('请描述问题');
      return;
    }
    if (contactController.text.trim().isEmpty) {
      Toast.show('请输入联系方式');
      return;
    }

    if (isSubmitting.value) return;
    isSubmitting.value = true;

    try {
      // 将图片文件转换为MultipartFile
      List<dio.MultipartFile>? fileList;
      if (imageList.isNotEmpty) {
        fileList = [];
        for (var image in imageList) {
          final multipartFile = await dio.MultipartFile.fromFile(
            image.path,
            filename: image.path.split('/').last,
          );
          fileList.add(multipartFile);
        }
      }

      final result = await DefaultApi().addFeedbackPost<Map<String, dynamic>>(
        descProblem: descriptionController.text.trim(),
        contactInfo: contactController.text.trim(),
        fileList: fileList,
      );

      if (result != null) {
        Toast.show('反馈已提交');
        Get.back();
      } else {
        Toast.show('提交失败，请重试');
      }
    } catch (e) {
      Toast.show('提交失败：${e.toString()}');
    } finally {
      isSubmitting.value = false;
    }
  }

  /// 跳转到反馈历史记录
  void goToFeedbackHistory() {
    Get.toNamed(SettingsRoutes.feedbackHistory);
  }
}
